package com.trustbook.visitor.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.trustbook.visitor.log.LogManager;

public class FileUtil {

	private static String TAG = "FileUtil";

	// Decode the bitmap and scale it down if necessary
	public static Bitmap decodeFile(File file) {
		LogManager.debug(TAG, "decodeFile -> Image File :" + file.getAbsolutePath());
		FileInputStream fin = null;
		try {
			InputStream is = null;
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			LogManager.debug(TAG, "o :" + o);
			Bitmap bm;
			o.inJustDecodeBounds = true;
			if (file != null) {
				fin = new FileInputStream(file);
				LogManager.debug(TAG, "fin :" + fin);
				bm = BitmapFactory.decodeStream(is, null, o);
				LogManager.debug(TAG, "is :" + is + " bm :" + bm);

				// now opts.outWidth and opts.outHeight are the dimension of the
				// bitmap, even though bm is null
				o.inJustDecodeBounds = false; // this will request the bm
				int sample_size = 4;
				try {
					long file_size = file.length() / 1024; // file length in kb
					LogManager.debug(TAG, "File lenght :" + file_size);

					if (file_size >= (10 * 1024)) {// greater than 10mb
						sample_size = 32; // scaled down by 32
					} else if (file_size >= (5 * 1024) && file_size < (10 * 1024)) { // between
																						// 5mb
																						// to
																						// 10mb
						sample_size = 16; // scaled down by 8
					} else if (file_size >= (2 * 1024) && file_size < (5 * 1024)) { // between
																					// 2mb
																					// to
																					// 5mb
						sample_size = 8; // scaled down by 4
					} else if (file_size / 2 >= 512 && file_size <= (2 * 1024)) { // between
																					// 512kb
																					// and
																					// 2mb
						sample_size = 4;
					} else if (file_size / 2 >= 100 && file_size / 2 <= 512) { // between
																				// 100kb
																				// to
																				// 512
																				// kb
						sample_size = 2;
					}
				} catch (Exception e) {
					LogManager.error(TAG, e.getMessage(), e);
				}

				LogManager.debug(TAG, "->Sampling to :" + sample_size);

				o.inSampleSize = sample_size; // scaled down by 4
				bm = BitmapFactory.decodeStream(fin, null, o);
				LogManager.debug(TAG, "return decodeFile() bm : " + bm);
				return bm;
			}
		} catch (FileNotFoundException e) {
			LogManager.error(TAG, e.getMessage(), e);
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					LogManager.error("ImageLoader", "Exception thrown", e);
				}
			}
		}
		LogManager.debug(TAG, "decodeFile returning null.");
		return null;
	}

}
